package com.neuedu.springmvc.convert;

import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 项目：springmvc-java4
 * 创建时间：  2022-03-23   14:28
 * 作者 :jshand
 * 描述 :
 */
public class String2DateConvert implements Converter<String, Date> {
    static List<SimpleDateFormat> sdfs = new ArrayList();
    static{
        sdfs.add(new SimpleDateFormat("yyyy-MM-dd"));
        sdfs.add(new SimpleDateFormat("yyyy/MM/dd"));
        sdfs.add(new SimpleDateFormat("yyyy-MM-dd"));
        sdfs.add(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"));
        sdfs.add(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

    }

    /**
     * String source  相当于  souece = request.getParameter("start");
     * String source  相当于  souece = request.getParameter("end");
     * @param source
     * @return
     */
    @Override
    public Date convert(String source) {
        //模式
//       Pattern p = Pattern.compile("%d{4}-%d{2}-%d{2}");
//
//        Matcher matcher = p.matcher(source);
//        if(matcher.matches()){
//            date = sdf[0].parse(source);
//        }else if

       
        Date date = null ;
        for (SimpleDateFormat sdf : sdfs) {
            try {
                date = sdf.parse(source);
                return date;

            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return date;
    }
}
